package com.xuecheng.getway.filter;

import com.alibaba.fastjson.JSON;
import com.xuecheng.commons.model.vo.AuthInfo;
import com.xuecheng.commons.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.SneakyThrows;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URLEncoder;

@Component
public class AuthFilter implements GlobalFilter, Ordered {
    /**
     * 过滤器的核心方法
     *  exchange：请求上下文（request和response）
     *  chain：过滤链（放行）
     */
    @SneakyThrows
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1、获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //2、过滤不需要校验token的请求
        //2.1、获取请求地址
        String path = request.getURI().getPath();
        //2.2、对于符合条件的放行
        if(path.contains("coursePub/preview") ||
                path.contains("auth/login") ||
                path.contains("basic/dictionary") ||
                path.contains("category/tree-nodes")||
                path.contains("course/upload")||
                path.contains("search/")){
            return chain.filter(exchange);
        }

        //3、获取请求头中的Authorization参数
        String token = request.getHeaders().getFirst("Authorization");
        //4、校验token，对于token异常的返回401状态码
        Boolean verifyToken = JwtUtils.verifyToken(token);
        if (!verifyToken) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //5、解析token（userId，companyId，companyName）
        Claims body = JwtUtils.parserToken(token).getBody();
        Long userId = body.get("userId", Long.class);
        Long companyId = body.get("companyId", Long.class);
        String name = body.get("companyName", String.class);

        //6、将用户信息，封装到Java对象
        AuthInfo info=new AuthInfo();
        info.setUid(userId);
        info.setCompanyId(companyId);
        info.setCompanyName(name);
        //7、向下传递，到其他的微服务
        //向请求头对象，设置用户信息
        String json = URLEncoder.encode(JSON.toJSONString(info), "UTF-8");
        ServerHttpRequest httpRequest = request.mutate().headers(httpHeaders -> {
            httpHeaders.set("payload", json);
        }).build();
        //将请求头对象，添加到请求中
        exchange.mutate().request(httpRequest);
        return chain.filter(exchange);
    }
    //过滤器的优先级
    @Override
    public int getOrder() {
        return 0;
    }
}
